"""
在线给验证码打标签
"""

from flask import Flask, request, render_template
import requests
import json
from gevent.pywsgi import WSGIServer
import time
import base64

import global_config
import util.img_utils as img_utils

app = Flask(__name__)


def getResultJson(status, v_img, v_code, msg=None):
    """
    获取结果的json字符串
    :param v_code:
    :param v_img:
    :param status: 结果状态
    :param msg: 信息
    :return:
    """
    result_json = {}
    result_json["status"] = status
    result_json["v_img"] = v_img
    result_json["v_code"] = v_code
    result_json["msg"] = msg
    return json.dumps(result_json, ensure_ascii=False)

@app.route('/getTagImg', methods=['GET'])
def app_get_tag_img():
    tag = ''
    base64_str = None
    i = 0
    while base64_str is None:
        base64_str, tag = global_config.preprocess_img.get_tag_img()
        i = i + 1
    print('获取 {} 次成功'.format(i))
    print('获取验证码成功')
    return getResultJson(True, base64_str, tag, '获取成功')

@app.after_request
def cors(environ):
    environ.headers['Access-Control-Allow-Origin']='*'
    environ.headers['Access-Control-Allow-Method']='*'
    environ.headers['Access-Control-Allow-Headers']='x-requested-with,content-type'
    return environ

@app.route('/tagImg', methods=['POST'])
def app_tagImg():
    try:
        if __name__ == '__main__':
            # 接受前端发来的数据
            s = time.time()
            data = json.loads(request.get_data())
            # result_data = discern(data)
            print(data)
            if len(data.get('img_tag')) != global_config.my_config.max_captcha:
                return getResultJson(False, "", "", "验证码字符数量不够")
            img_name = "{}-{}.{}".format(data.get('img_tag'), str(time.time()).replace(".", ""), 'png')
            img_utils.base64_to_image(data.get('v_img'), global_config.api_img_save_path_tag, img_name)
            e = time.time()
        # print('识别的信息为：{}，耗时：{} ms'.format(result_data, int((e - s) * 1000)))
        return getResultJson(True, "", "", "保存成功！非常感谢！！！")
    except BaseException as b:
        print("发生异常：{}".format(b))
        return getResultJson(False, "", "", "识别失败，参数错误")

@app.route('/', methods=['GET'])
def app_html_tag_img():
    return app.send_static_file('tag_img.html')

if __name__ == '__main__':
    # s = app_get_tag_img()
    # print(s)
    http_server = WSGIServer(('0.0.0.0', 80), app)
    print('服务器启动完成')
    http_server.serve_forever()
